<template>
    <div class="publish-article-body">
        <el-form :model="articleData" label-width="120px">
            <el-row>
                <h3 style="display: inline-block;">标题:</h3>
                <el-input v-model="articleData.title"
                          style="width: 40%; height: 50%; margin-left: 20px; margin-top: auto; margin-bottom: auto;"/>
            </el-row>

            <el-row>
                <v-md-editor :disabled-menus="[]" @upload-image="handleUploadImage" height="600px"
                             v-model="articleData.context"></v-md-editor>
            </el-row>
            <el-row>
                <el-text style="margin-right: 20px;margin-top: 10px;">摘要:</el-text>
                <el-input type="textarea" v-model="articleData.articleAbstract"/>
            </el-row>
            <div class="operation-body">
                <el-row>
                    <el-text style="margin-right: 20px;">分类:</el-text>
                    <el-select v-model="articleData.classificationId" placeholder="选择分类">
                        <el-option selected label="请选择" value="-1"/>
                        <el-option v-for="item in classifications" :key="item.id" :label="item.classificationName"
                                   :value="item.id"/>
                    </el-select>
                </el-row>
                <el-row style="margin-top:20px ;">
                    <el-text style="margin-right: 20px;">标签:</el-text>
                    <el-tag v-for="tag in articleData.tags" :key="tag.tagName" effect="dark" style="margin-right: 10px;"
                            closable :disable-transitions="false" @close="removeTag(tag)">
                        {{ tag.tagName }}
                    </el-tag>
                    <el-input v-if="config.tagInputShow" v-model="config.tagValue" size="small"
                              style="width: 100px; margin-right: 10px;" @keyup.enter="handleInputConfirm"
                              @blur="handleInputConfirm"/>
                    <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
                        + 添加
                    </el-button>
                    <el-button class="button-new-tag ml-1" type="danger" size="small" @click="clearAllTag">
                        清空
                    </el-button>
                </el-row>
                <el-row style="margin-top:20px ;">
                    <el-text style="margin-right: 20px;">仅自己可见</el-text>
                    <el-switch v-model="articleData.articleIsPrivate"/>
                </el-row>
                <el-row style="margin-top:50px ;">
                    <el-button type="success" :disabled="config.publishButtonDisable" style="width: 200px;"
                               @click="publish(false)">发布!
                    </el-button>
                    <el-button @click="publish(true)" :disable="config.publishButtonDisable">保存为草稿</el-button>
                </el-row>
            </div>
        </el-form>
        <br/><br/><br/><br/><br/><br/>
    </div>

</template>

<script>

import {useRouter} from 'vue-router'
import {reactive, onMounted} from 'vue'


import StringUtil from '../../utils/StringUtil.js'
import InfoUtil from '../../utils/InfoUtil.js'
import RequestUtil from '@/utils/RequestUtil.js'


export default {
    setup() {
        const router = useRouter();
        onMounted(() => {
            RequestUtil.sendGetRequest("/articleClassification/queryAll").then(
                (res) => {
                    if (res.code != 200) {
                        InfoUtil.warning(res.message);
                        return;
                    }
                    for (let i = 0; i < res.data.length; i++) {
                        classifications.push(res.data[i])
                    }

                }, (err) => {
                    InfoUtil.error("发送请求失败");
                    return;
                }
            )
        })
        const handleUploadImage = (event, insertImage, files) => {
            debugger
            // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
            RequestUtil.sendPostRequestUploadImg("/file/uploadArticleImg", {"img": files}).then(
                (response) => {
                    if (response.code != 200) {
                        InfoUtil.warning(response.message);
                        return;
                    }
                    let requestImgPath = RequestUtil.getRequestUrl("/file/article/img/?fileName=" + response.data);
                    // 此处只做示例
                    insertImage({
                        url: requestImgPath,
                        desc: files[0].name
                    });

                },
                (err) => {
                    console.log(err);
                    InfoUtil.error("上传图片失败");
                }
            )
        }

        const clearAllTag = () => {
            articleData.tags = [];
        }
        const removeTag = (tag) => {
            for (let i = 0; i < articleData.tags.length; i++) {
                if (articleData.tags[i].name == tag.name) {
                    articleData.tags.splice(i, 1);
                }
            }

        }
        //显示添加标签的input
        const showInput = () => {
            config.tagInputShow = true
        }
        //添加标签事件
        const handleInputConfirm = () => {
            if (StringUtil.isEmpty(config.tagValue)) {
                config.tagInputShow = false
                return;
            }
            for (let i = 0; i < articleData.tags.length; i++) {
                if (articleData.tags[i].tagName == config.tagValue) {
                    InfoUtil.warning(config.tagValue + "已经存在")
                    config.tagValue = "";
                    return;
                }
            }
            articleData.tags.push({tagName: config.tagValue});
            config.tagInputShow = false
            config.tagValue = ''
        }


        //发布按钮
        const publish = (articleIsDraft) => {
            if (StringUtil.isEmpty(articleData.title)) {
                InfoUtil.warning("标题不能为空");
                return;
            }
            if (StringUtil.isEmpty(articleData.context)) {
                InfoUtil.warning("内容不能为空");
                return;
            }
            if (articleData.classificationId == "-1") {
                InfoUtil.warning("请选择一个分类");
                return;
            }
            config.publishButtonDisable = true;
            const requestData = {
                article: {
                    title: articleData.title,
                    classificationId: articleData.classificationId,
                    content: articleData.context,
                    articleAbstract: articleData.articleAbstract,
                    articleIsPrivate: articleData.articleIsPrivate,
                    articleIsDraft: articleIsDraft
                },
                articleTags: articleData.tags
            }
            RequestUtil.sendPostRequest("/article/publish", requestData).then(
                (res) => {

                    if (res.code != 200) {
                        config.publishButtonDisable = false;
                        InfoUtil.warning(res.message)
                        return
                    }
                    if (!articleIsDraft) {
                        InfoUtil.success("操作成功,即将跳转到详情页")
                        setTimeout(() => {
                            router.push({
                                path: `/article-details/${res.data}`
                            });
                        }, 3000);
                    } else {
                        InfoUtil.success(res.message)
                    }


                }, (err) => {
                    config.publishButtonDisable = false;
                    InfoUtil.error("发送请求失败")
                }
            )
        }

        const config = reactive({
            tagInputShow: false,
            tagValue: "",
            publishButtonDisable: false
        })


        let articleData = reactive({
            context: "",
            title: "",
            classificationId: "-1",
            tags: [],
            articleIsPrivate: false,
            articleAbstract: ""
        });

        //分类
        let classifications = reactive([])

        return {
            articleData, classifications, config,
            showInput, handleInputConfirm, removeTag, clearAllTag, handleUploadImage, publish
        }

    }

}
</script>
<style scoped>
.publish-article-body{
    background-color: #fff;
    padding-right: 20px;
    padding-left: 20px;
}
.operation-body {
    width: 50%;
    padding-top: 20px;
    margin-left: 40%;
}
</style>
